<template>
  <view class="amap-location-picker">
    <!-- 顶部搜索栏 -->
    <view class="search-container">
      <view class="search-bar">
        <text class="iconfont ic-sousuo search-icon"></text>
        <input 
          class="search-input" 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索地点" 
          @input="onSearchInput"
          @confirm="searchLocation"
        />
        <text 
          v-if="searchKeyword" 
          class="iconfont ic-qingchu clear-icon" 
          @click="clearSearch"
        ></text>
      </view>
    </view>

    <!-- 地图容器 -->
    <view class="map-container">
      <map
        id="amap"
        class="map"
        :longitude="longitude"
        :latitude="latitude"
        :scale="scale"
        :markers="markers"
        :show-location="true"
        :enable-3D="false"
        :show-compass="false"
        :enable-overlooking="false"
        :enable-zoom="true"
        :enable-scroll="true"
        :enable-rotate="false"
        :enable-satellite="false"
        :enable-traffic="false"
        @markertap="onMarkerTap"
        @regionchange="onRegionChange"
        @tap="onMapTap"
      ></map>
      
      <!-- 中心点标记 -->
      <view class="center-marker">
        <text class="iconfont ic-dingwei marker-icon"></text>
      </view>
      
      <!-- 重新定位按钮 -->
      <view class="relocate-btn" @click="relocateToCurrentPosition">
        <text class="iconfont ic-dingwei2"></text>
      </view>
    </view>

    <!-- 搜索结果列表 -->
    <view v-if="showSearchResults" class="search-results">
      <scroll-view scroll-y class="results-scroll">
        <view 
          v-for="(item, index) in searchResults" 
          :key="index"
          class="result-item"
          @click="selectSearchResult(item)"
        >
          <view class="result-info">
            <view class="result-name">{{ item.name }}</view>
            <view class="result-address">{{ item.address }}</view>
          </view>
          <view class="result-distance" v-if="item.distance">
            {{ formatDistance(item.distance) }}
          </view>
        </view>
        
        <view v-if="searchResults.length === 0 && searchKeyword" class="no-results">
          <text>未找到相关地点</text>
        </view>
      </scroll-view>
    </view>

    <!-- 底部信息和确认按钮 -->
    <view class="bottom-info">
      <view class="location-info">
        <view class="location-name">{{ selectedLocation.name || '正在获取位置信息...' }}</view>
        <view class="location-address">{{ selectedLocation.address || '' }}</view>
      </view>
      
      <view class="confirm-btn" @click="confirmLocation">
        <text>确定</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getAddressByLocation, searchPOI } from '@/utils/amapApi.js'
import { safeGetLocation } from '@/utils/privacyUtil.js'

export default {
  name: 'AmapLocationPicker',
  props: {
    // 初始位置
    initialLocation: {
      type: Object,
      default: () => ({
        latitude: 39.908823,
        longitude: 116.397502,
        name: '',
        address: ''
      })
    }
  },
  data() {
    return {
      longitude: 116.397502, // 默认北京天安门
      latitude: 39.908823,
      scale: 16,
      markers: [],
      searchKeyword: '',
      searchResults: [],
      showSearchResults: false,
      selectedLocation: {
        name: '',
        address: '',
        latitude: 0,
        longitude: 0
      },
      mapContext: null,
      searchTimer: null
    }
  },
  mounted() {
    this.initMap();
    
    // 延迟初始化位置，给地图组件足够的时间渲染
    this.$nextTick(() => {
      setTimeout(() => {
        this.initLocation();
      }, 500);
    });
  },
  methods: {
    // 初始化地图
    initMap() {
      this.mapContext = uni.createMapContext('amap', this);
    },
    
    // 初始化位置
    initLocation() {
      console.log('初始化位置，传入的位置信息:', this.initialLocation);
      
      if (this.initialLocation.latitude && this.initialLocation.longitude && 
          this.initialLocation.latitude !== 0 && this.initialLocation.longitude !== 0) {
        console.log('使用传入的初始位置');
        this.longitude = this.initialLocation.longitude;
        this.latitude = this.initialLocation.latitude;
        this.selectedLocation = { ...this.initialLocation };
        
        // 如果有位置信息但没有地址，尝试获取地址
        if (!this.selectedLocation.address || !this.selectedLocation.name) {
          this.getLocationInfo(this.latitude, this.longitude);
        }
      } else {
        console.log('没有初始位置，获取当前位置');
        // 显示友好提示
        uni.showToast({
          title: '正在获取您的位置...',
          icon: 'loading',
          duration: 2000
        });
        this.getCurrentLocation();
      }
    },
    
    // 获取当前位置
    getCurrentLocation() {
      // 显示加载状态
      uni.showLoading({
        title: '正在获取位置...',
        mask: true
      });
      
      safeGetLocation()
        .then(res => {
          uni.hideLoading();
          console.log('获取位置成功:', res);
          this.longitude = res.longitude;
          this.latitude = res.latitude;
          this.getLocationInfo(res.latitude, res.longitude);
        })
        .catch(err => {
          uni.hideLoading();
          console.error('获取位置失败:', err);
          
          let errorMsg = '获取位置失败';
          if (err.message) {
            if (err.message.includes('privacy') || err.message.includes('隐私')) {
              errorMsg = '请先同意隐私协议并授权位置权限';
            } else if (err.message.includes('auth') || err.message.includes('权限')) {
              errorMsg = '位置权限被拒绝，请在设置中开启位置权限';
            } else {
              errorMsg = err.message;
            }
          }
          
          uni.showModal({
            title: '定位失败',
            content: errorMsg + '，将使用默认位置（北京天安门）',
            showCancel: false,
            confirmText: '我知道了',
            success: () => {
              // 使用默认位置（北京天安门）
              this.longitude = 116.397502;
              this.latitude = 39.908823;
              this.getLocationInfo(this.latitude, this.longitude);
            }
          });
        });
    },
    
    // 重新定位到当前位置
    relocateToCurrentPosition() {
      this.getCurrentLocation();
    },
    
    // 地图点击事件
    onMapTap(e) {
      const { latitude, longitude } = e.detail;
      this.latitude = latitude;
      this.longitude = longitude;
      this.getLocationInfo(latitude, longitude);
      this.hideSearchResults();
    },
    
    // 地图区域变化事件
    onRegionChange(e) {
      if (e.type === 'end') {
        // 获取地图中心点位置信息
        this.mapContext.getCenterLocation({
          success: (res) => {
            this.latitude = res.latitude;
            this.longitude = res.longitude;
            this.getLocationInfo(res.latitude, res.longitude);
          }
        });
      }
    },
    
    // 标记点击事件
    onMarkerTap(e) {
      const marker = this.markers.find(m => m.id === e.markerId);
      if (marker) {
        this.selectedLocation = {
          name: marker.title,
          address: marker.address,
          latitude: marker.latitude,
          longitude: marker.longitude
        };
      }
    },
    
    // 获取位置信息（逆地理编码）
    getLocationInfo(latitude, longitude) {
      // 显示加载状态
      uni.showLoading({
        title: '获取地址信息...',
        mask: true
      });
      
      // 调用高德地图逆地理编码API
      getAddressByLocation(longitude, latitude)
        .then(result => {
          uni.hideLoading();
          this.selectedLocation = {
            name: result.name || '未知地点',
            address: result.address || result.name || '详细地址获取失败',
            latitude: latitude,
            longitude: longitude
          };
          console.log('获取地址信息成功:', this.selectedLocation);
        })
        .catch(err => {
          uni.hideLoading();
          console.error('逆地理编码失败:', err);
          
          // 如果API调用失败，使用坐标作为备选方案
          this.selectedLocation = {
            name: '选中位置',
            address: `纬度: ${latitude.toFixed(6)}, 经度: ${longitude.toFixed(6)}`,
            latitude: latitude,
            longitude: longitude
          };
          
          // 显示友好的错误提示
          uni.showToast({
            title: '地址解析失败，但位置已选中',
            icon: 'none',
            duration: 2000
          });
        });
    },
    
    // 搜索输入事件
    onSearchInput() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      
      this.searchTimer = setTimeout(() => {
        if (this.searchKeyword.trim()) {
          this.searchLocation();
        } else {
          this.hideSearchResults();
        }
      }, 500);
    },
    
    // 搜索地点
    searchLocation() {
      if (!this.searchKeyword.trim()) {
        return;
      }
      
      // 显示搜索加载状态
      uni.showLoading({
        title: '搜索中...',
        mask: false
      });
      
      // 调用高德地图POI搜索API
      searchPOI(this.searchKeyword)
        .then(result => {
          uni.hideLoading();
          
          if (result && result.results && result.results.length > 0) {
            this.searchResults = result.results.map(poi => ({
              name: poi.name,
              address: poi.address,
              latitude: poi.latitude,
              longitude: poi.longitude,
              distance: poi.distance
            }));
            this.showSearchResults = true;
            console.log(`搜索到 ${this.searchResults.length} 个结果`);
          } else {
            this.searchResults = [];
            this.showSearchResults = true;
            uni.showToast({
              title: '未找到相关地点',
              icon: 'none',
              duration: 1500
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          console.error('搜索失败:', err);
          
          // 如果API调用失败，显示空结果
          this.searchResults = [];
          this.showSearchResults = true;
          
          let errorMsg = '搜索失败，请重试';
          if (err.message && err.message.includes('INVALID_USER_KEY')) {
            errorMsg = '地图服务配置错误';
          } else if (err.message && err.message.includes('network')) {
            errorMsg = '网络连接失败，请检查网络';
          }
          
          uni.showToast({
            title: errorMsg,
            icon: 'none',
            duration: 2000
          });
        });
    },
    
    // 选择搜索结果
    selectSearchResult(item) {
      this.latitude = item.latitude;
      this.longitude = item.longitude;
      this.selectedLocation = {
        name: item.name,
        address: item.address,
        latitude: item.latitude,
        longitude: item.longitude
      };
      
      // 添加标记
      this.markers = [{
        id: 1,
        latitude: item.latitude,
        longitude: item.longitude,
        title: item.name,
        address: item.address,
        iconPath: '/static/map-marker.png',
        width: 30,
        height: 30,
        callout: {
          content: item.name,
          color: '#333',
          fontSize: 12,
          borderRadius: 5,
          bgColor: '#fff',
          padding: 5,
          display: 'ALWAYS'
        }
      }];
      
      this.hideSearchResults();
      this.clearSearch();
    },
    
    // 清除搜索
    clearSearch() {
      this.searchKeyword = '';
      this.hideSearchResults();
    },
    
    // 隐藏搜索结果
    hideSearchResults() {
      this.showSearchResults = false;
      this.searchResults = [];
    },
    
    // 格式化距离
    formatDistance(distance) {
      if (distance < 1000) {
        return `${distance}m`;
      } else {
        return `${(distance / 1000).toFixed(1)}km`;
      }
    },
    
    // 确认选择位置
    confirmLocation() {
      if (!this.selectedLocation.name) {
        uni.showToast({
          title: '请选择位置',
          icon: 'none'
        });
        return;
      }
      
      this.$emit('confirm', {
        name: this.selectedLocation.name,
        address: this.selectedLocation.address,
        latitude: this.selectedLocation.latitude,
        longitude: this.selectedLocation.longitude
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.amap-location-picker {
  width: 100%;
  height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
}

.search-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10rpx);
  
  .search-bar {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 50rpx;
    padding: 0 30rpx;
    height: 80rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    
    .search-icon {
      font-size: 36rpx;
      color: #999;
      margin-right: 20rpx;
    }
    
    .search-input {
      flex: 1;
      font-size: 28rpx;
      height: 80rpx;
    }
    
    .clear-icon {
      font-size: 32rpx;
      color: #999;
      padding: 10rpx;
    }
  }
}

.map-container {
  flex: 1;
  position: relative;
  
  .map {
    width: 100%;
    height: 100%;
  }
  
  .center-marker {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -100%);
    z-index: 5;
    
    .marker-icon {
      font-size: 60rpx;
      color: #ff4d4f;
      filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.3));
    }
  }
  
  .relocate-btn {
    position: absolute;
    bottom: 200rpx;
    right: 30rpx;
    width: 80rpx;
    height: 80rpx;
    background: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    
    .iconfont {
      font-size: 40rpx;
      color: #14cc60;
    }
  }
}

.search-results {
  position: absolute;
  top: 120rpx;
  left: 20rpx;
  right: 20rpx;
  max-height: 60vh;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.1);
  z-index: 15;
  
  .results-scroll {
    max-height: 60vh;
    
    .result-item {
      display: flex;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:active {
        background-color: #f8f8f8;
      }
      
      .result-info {
        flex: 1;
        
        .result-name {
          font-size: 32rpx;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .result-address {
          font-size: 26rpx;
          color: #666;
        }
      }
      
      .result-distance {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .no-results {
      padding: 60rpx;
      text-align: center;
      color: #999;
      font-size: 28rpx;
    }
  }
}

.bottom-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 30rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
  
  .location-info {
    margin-bottom: 30rpx;
    
    .location-name {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .location-address {
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
    }
  }
  
  .confirm-btn {
    width: 100%;
    height: 80rpx;
    background: #14cc60;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    text {
      font-size: 32rpx;
      color: #fff;
      font-weight: 600;
    }
    
    &:active {
      background: #11b051;
    }
  }
}
</style> 